﻿// test.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <fstream>
#include <thread>
#include <functional>
#include "../include/Config.h"
#include "../include/Server.h"

#ifdef _WIN32
#	ifdef _WIN64
#		ifdef _DEBUG
#			pragma comment(lib, "../x64/Debug/async_curl.lib")
#		else
#			pragma comment(lib, "../x64/Release/async_curl.lib")
#		endif
#	else
#		ifdef _DEBUG
#			pragma comment(lib, "../Debug/async_curl.lib")
#		else
#			pragma comment(lib, "../Release/async_curl.lib")
#		endif
#	endif
#endif

using namespace std;

struct MyCallBack: public CurlCallBack
{
	virtual int operator() (MsgPack* pack)
	{
		HttpMsgPack* http_pack = dynamic_cast<HttpMsgPack*>(pack);

		if (http_pack->_errMsg.empty())
		{
			// 输出到文件
			string filename = "out_" + to_string(pack->_msgid) + ".txt";
			fstream o(filename, ios::in | ios::out | ios::trunc);
			o << http_pack->_rspData;
			o.close();

			// 输出到屏幕
			cout << http_pack->_rspData;
		}
		else
		{
			cout << "error:" << http_pack->_errMsg;
		}

		return 0;
	}
};

int main()
{
	// 配置
	HttpConfig config;
	config._timeout = 30;

	// 服务
	Server* server = Server::CreateHttp(WriteLogConsole);

	// 初始化
	server->Init(&config);

	MyCallBack mycallback;
	server->SetCallBack(&mycallback);

	thread thr(std::bind(&Server::Run, server));

	/*
		投递消息：
		默认投递get方法，目前不加任何头部字段信息；
		只加了一个Content-Type:application/x-www-form-urlencoded;charset=UTF-8,
		改头部信息由pack._format = HttpContextFormat::URLENCODED指定
	 */
	int numcount = 100;
	while (--numcount > 0)
	{
		HttpMsgPack pack;
		pack._format = HttpContextFormat::URLENCODED;
		pack._url = "www.baidu.com";
		server->PostPack(&pack);
		this_thread::sleep_for(chrono::seconds(2));
	}

	thr.join();

	return 0;
}
